<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;
use app\common\model\QimenDunjiaLog;

/**
 * 奇门遁甲接口
 * @ApiWeigh (92)
 */
class QimenDunjia extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 奇门遁甲排盘
     * 
     * @ApiTitle    (奇门遁甲排盘)
     * @ApiSummary  (根据用户信息进行奇门遁甲排盘分析)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/qimen_dunjia/index)
     * 
     * @ApiParams   (name="name", type="string", required=true, description="姓名")
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="type", type="integer", required=true, description="历类型：0=农历，1=公历")
     * @ApiParams   (name="year", type="integer", required=true, description="起盘年，如：1988")
     * @ApiParams   (name="month", type="integer", required=true, description="起盘月，如：8")
     * @ApiParams   (name="day", type="integer", required=true, description="起盘日，如：7")
     * @ApiParams   (name="hours", type="integer", required=true, description="起盘时，如：12")
     * @ApiParams   (name="minute", type="integer", required=false, description="起盘分，如：30")
     * @ApiParams   (name="ju_model", type="integer", required=false, description="起局方法：0=拆补法,1=置闰法,2=茅山道人法", default=0)
     * @ApiParams   (name="pan_model", type="integer", required=false, description="盘类型：0=飞盘奇门,1=转盘奇门", default=1)
     * @ApiParams   (name="fei_pan_model", type="integer", required=false, description="飞盘排法：1=全部顺排,2=阴顺阳逆", default=1)
     * @ApiParams   (name="zhen", type="integer", required=false, description="是否真太阳时：1=考虑真太阳时,2=不考虑真太阳时", default=2)
     * @ApiParams   (name="province", type="string", required=false, description="省份，如：北京市")
     * @ApiParams   (name="city", type="string", required=false, description="城市，如：北京")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "sex": "男",                      // 性别
          "type": "公历",                   // 历法类型
          "gongli": "2024-02-23 17:06:00",  // 公历时间
          "nongli": "二〇二years正月十四日", // 农历时间
          "ju_model": "拆补法",             // 起局方法
          "pan_model": "转盘奇门",          // 盘类型
          "ju_name": "上元甲子局",          // 局名
          "ju_shen": "值符",                // 值使
          "ju_xing": "天心",                // 值星
          "ju_men": "休门",                 // 值门
          "analysis": "..."                 // 排盘分析
        }
      })
     */
    public function index()
    {
        $params = [
            'name' => $this->request->post('name', '', 'trim'),
            'sex' => $this->request->post('sex', 0, 'intval'),
            'type' => $this->request->post('type', 0, 'intval'),
            'year' => $this->request->post('year', '', 'intval'),
            'month' => $this->request->post('month', '', 'intval'),
            'day' => $this->request->post('day', '', 'intval'),
            'hours' => $this->request->post('hours', '', 'intval'),
            'minute' => $this->request->post('minute', null, 'intval'),
            'ju_model' => $this->request->post('ju_model', 0, 'intval'),
            'pan_model' => $this->request->post('pan_model', 1, 'intval'),
            'fei_pan_model' => $this->request->post('fei_pan_model', 1, 'intval'),
            'zhen' => $this->request->post('zhen', 2, 'intval'),
            'province' => $this->request->post('province', ''),
            'city' => $this->request->post('city', '')
        ];

        // 必填参数验证
        $required = ['name', 'sex', 'type', 'year', 'month', 'day', 'hours'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if (!in_array($params['type'], [0, 1])) {
            $this->error(__('Invalid type value'));
        }
        if ($params['ju_model'] < 0 || $params['ju_model'] > 2) {
            $this->error(__('Invalid ju_model value'));
        }
        if (!in_array($params['pan_model'], [0, 1])) {
            $this->error(__('Invalid pan_model value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Liupan/qimendunjia', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '奇门遁甲排盘分析失败');
            }
            
            // // 记录查询日志
            // $logName = sprintf(
            //     "%s年%s月%s日%s时%s", 
            //     $params['year'],
            //     $params['month'],
            //     $params['day'],
            //     $params['hours'],
            //     ['农历', '公历'][$params['type']]
            // );
            
            QimenDunjiaLog::create(array_merge(
                $params,
                [
                    'user_id' => $this->auth->id,
                    //'name' => $logName,
                    'response_data' => json_encode($result['data'], JSON_UNESCAPED_UNICODE)
                ]
            ));
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }

    /**
     * 查询历史列表
     * 
     * @ApiTitle    (奇门遁甲历史记录)
     * @ApiSummary  (获取用户的奇门遁甲查询历史记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/qimen_dunjia/history)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量", default=10)
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "total": 100,                     // 总记录数
          "list": [{
            "id": 1,                        // 记录ID
            "name": "2024年2月23日17时公历", // 记录名称
            "sex": 0,                       // 性别
            "sex_text": "男",               // 性别文字
            "type": 1,                      // 历类型
            "type_text": "公历",            // 历类型文字
            "year": 2024,                   // 年
            "month": 2,                     // 月
            "day": 23,                      // 日
            "hours": 17,                    // 时
            "createtime": 1677123456,       // 创建时间戳
            "createtime_text": "2023-02-23 12:34:56" // 创建时间文字
          }]
        }
      })
     */
    public function history()
    {
        $page = $this->request->get('page', 1, 'intval');
        $limit = $this->request->get('limit', 10, 'intval');
        
        $total = QimenDunjiaLog::where('user_id', $this->auth->id)->count();
        $list = QimenDunjiaLog::where('user_id', $this->auth->id)
            ->field('id,name,sex,type,year,month,day,hours,createtime,ju_model,pan_model,fei_pan_model,zhen')
            ->order('id desc')
            ->page($page, $limit)
            ->select();
        
        $this->success('获取成功', [
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * 查询历史详情
     * 
     * @ApiTitle    (奇门遁甲历史详情)
     * @ApiSummary  (获取指定奇门遁甲记录的详细信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/qimen_dunjia/detail)
     * @ApiParams   (name="id", type="integer", required=true, description="记录ID")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "id": 1,                          // 记录ID
          "user_id": 1,                     // 用户ID
          "name": "2024年2月23日17时公历",  // 记录名称
          "sex": 0,                         // 性别
          "sex_text": "男",                 // 性别文字
          "type": 1,                        // 历类型
          "type_text": "公历",              // 历类型文字
          "year": 2024,                     // 年
          "month": 2,                       // 月
          "day": 23,                        // 日
         "hours": 17,                      // 时
          "minute": 30,                     // 分
          "ju_model": 0,                    // 起局方法
          "ju_model_text": "拆补法",        // 起局方法文字
          "pan_model": 1,                   // 盘类型
          "pan_model_text": "转盘奇门",     // 盘类型文字
          "fei_pan_model": 1,               // 飞盘排法
          "fei_pan_model_text": "全部顺排", // 飞盘排法文字
          "zhen": 2,                        // 是否真太阳时
          "zhen_text": "不考虑真太阳时",    // 真太阳时文字
          "province": "北京市",             // 省份
          "city": "北京",                   // 城市
          "createtime": 1677123456,         // 创建时间戳
          "createtime_text": "2023-02-23 12:34:56", // 创建时间文字
          "response_data": {                // 原始接口返回数据
            // ... 同奇门遁甲接口返回的data部分
          }
        }
      })
     */
    public function detail()
    {
        $id = $this->request->get('id', 0, 'intval');
        
        $log = QimenDunjiaLog::where('user_id', $this->auth->id)
            ->where('id', $id)
            ->find();
            
        if (!$log) {
            $this->error('记录不存在');
        }
        
        $log['response_data'] = json_decode($log['response_data'], true);
        
        $this->success('获取成功', $log);
    }

    /**
     * 清空历史记录
     * 
     * @ApiTitle    (清空奇门遁甲历史记录)
     * @ApiSummary  (清空当前用户的所有奇门遁甲查询记录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/qimen_dunjia/clearHistory)
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "清空成功",
     *   "data": null
     * })
     */
    public function clearHistory()
    {
        try {
            QimenDunjiaLog::where('user_id', $this->auth->id)->delete();
            $this->success('清空成功');
        } catch (\think\exception\PDOException $e) {
            $this->error('清空失败：' . $e->getMessage());
        }
    }
}